import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.saierzy.cn',
  timeout: 15000,
});

// 统一检查返回码
function ensureOk(data, fallbackMsg) {
  if (!data || Number(data.code) !== 200) {
    const err = new Error(data?.msg || fallbackMsg || '服务异常');
    err.code = data?.code;
    throw err;
  }
  return data;
}

// 列表搜索接口（GET），适配返回结构 { code, data: { item_list, has_more }, msg }
export async function searchItems({ page = 1, size = 10, keyword = '', cate_id }) {
  const params = { query: keyword, page, page_size: size };
  if (cate_id != null && cate_id !== '') params.cate_id = cate_id;
  params.is_admin = true;
  const res = await api.get('/v1/item/search', { params });
  const root = ensureOk(res?.data, '获取列表失败');
  const data = root.data || {};
  
  const records = Array.isArray(data.item_list) ? data.item_list : [];
  const hasMore = Boolean(data.has_more);
  const total = data.total_count;
  return { list: records, total, hasMore };
}

// 创建设备（POST）
export async function createItem(payload) {
  const res = await api.post('/v1/item/create', payload);
  return ensureOk(res?.data, '添加失败');
}

// 更新设备（POST）
export async function updateItem(payload) {
  const res = await api.post('/v1/item/update', payload);
  return ensureOk(res?.data, '更新失败');
}

// 删除设备（POST）
export async function deleteItem(payload) {
  const res = await api.post('/v1/item/delete', payload);
  return ensureOk(res?.data, '删除失败');
}

// 显示/隐藏（POST）
export async function showItem(payload) {
  const res = await api.post('/v1/item/update/show', payload);
  return ensureOk(res?.data, '更新展示状态失败');
}

// 上传图片（POST）
export async function uploadImage(formData) {
  const res = await api.post('/v1/upload/image', formData, {
    headers: { 'Content-Type': 'multipart/form-data' },
  });
  return ensureOk(res?.data, '上传失败');
}

export default api;
